//引入fs模块
const fs = require('fs')
//引入path模块
const path = require('path')

//读取index.html原文件内的内容
fs.readFile(
  path.join(__dirname, '/素材/index.html'),
  'utf-8',
  function (err, dataStr) {
    if (err) return console.log(err)

    const cssReg = /<style>([\s\S]*)<\/style>/
    const jsReg = /<script>([\s\S]*)<\/script>/

    //css样式提取
    let styleStr = cssReg.exec(dataStr)[0]
    //css的内容
    let cssStr = cssReg.exec(dataStr)[1]

    //js提取
    let scriptStr = jsReg.exec(dataStr)[0]
    let jsStr = jsReg.exec(dataStr)[1]

    //写入css到文件中
    fs.writeFile(
      path.join(__dirname, './clock/index.css'),
      cssStr,
      'utf-8',
      function (err) {
        if (err) return console.log(err)

        console.log('写入成功')
      }
    )

    //写入js到文件中
    fs.writeFile(
      path.join(__dirname, './clock/index.js'),
      jsStr,
      'utf-8',
      function (err) {
        if (err) return console.log(err)

        console.log('写入成功')
      }
    )

    //先将html中的内容做替换
    let htmlStr = dataStr
      .replace(styleStr, '<link rel="stylesheet" href="./index.css"/>')
      .replace(scriptStr, '<script src="./index.js"></script>')

    //写入html到文件中
    fs.writeFile(
      path.join(__dirname, './clock/index.html'),
      htmlStr,
      'utf-8',
      function (err) {
        if (err) return console.log(err)

        console.log('写入成功')
      }
    )
  }
)
